<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
    <title>发布问题 - 码匠论坛</title>
    <link rel="stylesheet" th:href="@{/static/layui/css/layui.css}" media="all"/>
    <link rel="stylesheet" th:href="@{/static/common/custom.css}" media="all"/>
    <link rel="stylesheet" th:href="@{/static/css/publish.css}" media="all"/>
    <link rel="stylesheet" th:href="@{/static/fontawesome/css/fontawesome.min.css}" media="all"/>
    <script th:src="@{/static/common/jquery.min.js}"></script>
    <script th:src="@{/static/js/qiniu.min.js}"></script>
    <script src="/static/plupload/plupload.full.min.js"></script>
    <script src="/static/plupload/wangEditor/wangEditor.min.js"></script>
    <script th:src="@{/static/layui/layui.js}"></script>
    <script th:src="@{/static/js/search.js}"></script>
    <script th:src="@{/static/js/forum.js}"></script>
    <script th:src="@{/static/js/emoji.js}"></script>
</head>
<body>
<div class="layui-layout layui-layout-admin">
    <header th:replace="common/header"></header>
    <fieldset class="layui-elem-field layui-field-title">
        <legend>发起提问</legend>
    </fieldset>

    <div class="layui-col-xs8" style="margin-left: 3%;margin-bottom: 100px">
        <form class="layui-form layui-form-pane" method="post">
            <div class="layui-form-item">
                <label class="layui-form-label">问题标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" lay-verify="title" autocomplete="off" placeholder="请输入标题"
                           class="layui-input">
                </div>
            </div>
            <!--wangEditor富文本编辑器-->
            <div id="editor" class="text"></div>
            <!-- 添加标签 -->
            <div style="height: 10px"></div>
            <div class="layui-form-item">
                <label class="layui-form-label">问题标签</label>
                <div class="layui-input-block">
                    <input type="text" name="tag" id="question-tag" lay-verify="tag" autocomplete="off"
                           placeholder="请输入标签名称，用英文逗号分隔"
                           class="layui-input">
                </div>
            </div>
            <!-- 数据库标签选择 -->
            <div class="layui-tab" id="forum-tags"></div>

            <div style="height: 20px"></div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" style="float: right;border-radius: 10px" class="layui-btn"
                            lay-submit=""
                            lay-filter="publish"><i style="font-size: 15px;font-weight: 500"
                                                    class="layui-icon layui-icon-survey">发布问题</i></button>
                </div>
            </div>
        </form>
    </div>
    <div class="layui-col-xs3" style="margin-left: 4%">

        <div id="publishInfo">
            <div class="info">
                <h1 style="text-align: center"><i class="fa fa-university" aria-hidden="true"></i>&nbsp;问题发起指南</h1>
                <ol>
                    <li>问题标题: 请用精简的语言描述您发布的问题，不超过 50 字</li>
                    <li>问题补充: 详细补充您的问题内容，并确保问题描述清晰直观, 并提供一些相关的资料</li>
                    <li>选择标签: 选择一个或者多个合适的标签，用逗号隔开，每个标签不超过 10 个字</li>
                </ol>
            </div>
        </div>
    </div>

    <script th:inline="javascript">

        let loginUserInfo = [[${session.loginUserInfo}]];
        init(loginUserInfo);

        layui.use(['element', 'form', 'layedit', 'jquery'], function () {
            let element = layui.element;
            let layedit = layui.layedit;
            let form = layui.form;
            element.init();

            $("#title-publish").addClass("layui-this");

            //面包屑使用
            let currPoisition = "<span lay-separator=\"\">&gt;</span><a><cite>发起提问</cite></a>";
            $(".layui-breadcrumb a").last().after(currPoisition);

            //配置图片上传
            layedit.set({
                uploadImage: {
                    url: '/uploadImage'
                    , type: ''
                }
            });

            //配置wangEditor富文本编辑器
            let E = window.wangEditor;
            let editor = new E('#editor');

            editor.customConfig.debug = true;
            // editor.customConfig.customAlert = function (info) {
            //     // info 是需要提示的内容
            //     alert('上传图片助手：' + info)
            // };

            //wangEditor配置
            editor.customConfig.uploadImgServer = '/uploadQuestionImages';  // 上传图片到服务器
            // editor.customConfig.qiniu = true
            editor.customConfig.uploadImgShowBase64 = true;   // 使用 base64 保存图片
            editor.customConfig.uploadImgTimeout = 100000000;
            editor.customConfig.uploadImgMaxSize = 20 * 1024 * 1024;  //图片最大20M
            editor.customConfig.uploadImgMaxLength = 5;
            editor.customConfig.uploadFileName = 'ques';
            // editor.customConfig.showLinkImg = false;   //是否关闭在线图片链接

            editor.customConfig.uploadImgHooks = {
                fail: function (xhr, editor, result) {
                    // 图片上传并返回结果，但图片插入错误时触发
                    // xhr 是 XMLHttpRequst 对象，editor 是编辑器对象，result 是服务器端返回的结果
                    layer.msg("图片插入失败");
                },
                error: function (xhr, editor) {
                    layer.msg("图片上传失败");
                },
                timeout: function (xhr, editor) {
                    layer.msg("图片上传超时");
                },
            };

            //配置表情包
            initEmoji(editor);

            editor.create();

            //表单验证
            form.verify({
                title: function (title) {
                    if (title == null || ($.trim(title).length === 0)) {
                        return '标题不能为空哦';
                    }
                    if (title.length < 1 || title.length > 50) {
                        return '标题必须在50个字符以内';
                    }
                }
                , tag: function (tag) {
                    if (tag == null || ($.trim(tag).length === 0)) {
                        return '至少填写一个标签哦';
                    }
                    if (tag.indexOf("，") > 0) {
                        return '请使用英文逗号分隔标签哦';
                    }
                    let regex = /[+,#-x22]+/;
                    let reg = /[\u4E00-\u9FA5\uF900-\uFA2D]/;
                    if (!tag.match(regex) && !tag.match(reg)) {
                        return '请不要输入除+,#-之外的特殊字符哦';
                    }
                }
            });

            //选中导航栏，并且使用面包屑导航
            $('.layui-header li').click(function () {
                $(this).addClass('layui-this').siblings().removeClass('layui-this');
            });

            //监听问题提交
            form.on('submit(publish)', function (data) {
                //提交前的校验数据
                if (data.field.title == null || ($.trim(data.field.title).length === 0)) {
                    layer.msg("标题不能为空哦", {icon: 0, time: 2000});
                    return false;
                }
                if (($.trim(data.field.title).length > 50)) {
                    layer.msg("标题不能超过50个字符哦", {icon: 0, time: 2000});
                    return false;
                }
                //验证输入内容不能为空
                let summary = editor.txt.html();
                if (summary.replace(/<.*?>/g, "") === null || summary.replace(/<.*?>/g, "") === "") {
                    layer.msg("输入内容不能为空", {icon: 0, time: 2000});
                    return false;
                }

                //标签不能为空
                if (data.field.tag == null || ($.trim(data.field.tag).length === 0)) {
                    layer.msg("至少填写一个标签哦", {icon: 0, time: 2000});
                    return false;
                }

                //标签中不能添加重复
                let tag = data.field.tag;
                if (tag.indexOf(",") !== -1) {
                    let tags = tag.split(",");
                    if (tags.length > 10) {
                        layer.msg("最多允许添加10个标签哦", {icon: 0, time: 2000});
                        return false;
                    }
                    for (let i = 0; i < tags.length - 1; i++) {
                        for (let j = i + 1; j < tags.length; j++) {
                            if (tags[i].toLowerCase() === tags[j].toLowerCase()) {
                                layer.msg("同一个标签不能重复添加哦", {icon: 0, time: 2000});
                                return false;
                            }
                        }
                    }
                }

                $.ajax({
                    type: "post",
                    url: "/publish",
                    data: {
                        title: data.field.title,
                        description: editor.txt.html(),
                        tag: data.field.tag
                    },
                    success: function (res) {
                        if (res.status === 200) {
                            layer.alert("发布问题成功，积分+3", {icon: 6, time: 2000}, function () {
                                window.location.href = "/";
                            });
                        } else if (res.status === 500) {
                            layer.alert(res.msg, {icon: 5, time: 2000});
                        } else if (res.status === 400) {
                            layer.alert(res.msg, {icon: 5, time: 2000});
                        }
                    },
                    error: function () {
                        layer.alert("系统错误，请稍后再试", {icon: 5, time: 2000});
                    }
                });
                return false;
            });
        });

        //获取标签框聚焦事件
        $("#question-tag").focus(function () {
            //光标聚焦，开始获取分类数据
            let tHtml = getCategories();

            //再获取每个分类下的标签数据
            let tagHtml = getTags();

            $("#forum-tags").html(tHtml + tagHtml);
        });

        //增加标签
        function addTag(obj) {
            // alert($(obj).text());
            let tag = $(obj).text();
            let text = $("#question-tag").val();
            if ($.trim(text).length > 0) {
                //输入框中已经存在tag，提示信息
                let temp = text.split(",");
                if (temp.length > 4) {
                    layer.alert("不能添加超过 5 个标签哦", {icon: 5, time: 2000});
                    return false;
                }
                for (let i = 0; i < temp.length; i++) {
                    if (temp[i] === tag) {
                        layer.alert(tag + " 标签已存在，请勿重复添加哦", {icon: 5, time: 2000});
                        return false;
                    }
                }
                //否则不存在，可以直接添加
                $("#question-tag").val(text + "," + tag);
            } else {
                $("#question-tag").val(tag);
            }
        }


        let categoryInfo = "";

        //查询所有分类
        function getCategories() {
            let html = "<ul class=\"layui-tab-title\" id=\"tags-tab\">";
            $.ajax({
                type: "get",
                url: "/getCategories",
                async: false,
                success: function (res) {
                    if (res.status === 200) {
                        let categories = JSON.parse(res.data);
                        categoryInfo = categories;
                        for (let i = 0; i < categories.length; i++) {
                            if (i === 0) {
                                html += "<li class='layui-this'>" + categories[0].category + "</li>";
                            } else {
                                html += "<li>" + categories[i].category + "</li>";
                            }
                        }
                    }
                },
                error: function () {
                    layer.alert("无法查询到标签信息，请稍后再试", {icon: 5, time: 2000});
                }
            });
            return html + "</ul>";
        }

        //查询所有标签
        function getTags() {
            let html = "";
            $.ajax({
                type: "get",
                url: "/getTags",
                async: false,
                success: function (res) {
                    //回调返回结果
                    if (res.status === 200) {
                        let tags = JSON.parse(res.data);

                        for (let i = 0; i < categoryInfo.length; i++) {
                            //拼接html，添加开头
                            if (i === 0) {
                                html += "<div class=\"layui-tab-content\" id=\"tags-tag\"><div class=\"layui-tab-item layui-show\">";
                            } else {
                                html += "<div class=\"layui-tab-item\">";
                            }

                            //添加中间标签体
                            for (let j = 0; j < tags.length; j++) {
                                if (categoryInfo[i].id === tags[j].categoryId) {
                                    //添加html

                                    html += " <div class=\"hot_tag\">\n" +
                                        "        <div>" +
                                        "             <a class=\"tagname\" onclick='addTag(this)' href=\"javascript:;\"><span>" + tags[j].tagsName + "</span></a>\n" +
                                        "        </div>\n" +
                                        "      </div>";
                                }
                            }

                            //添加末尾
                            html += "</div>";
                        }
                    }
                },
                error: function () {
                    layer.alert("无法查询到标签信息，请稍后再试", {icon: 5, time: 2000});
                }
            });
            return html + "</div>";
        }
    </script>
    <!--    <footer th:replace="common/footer"></footer>-->
</div>
</body>
</html>